layui.define(['element', 'api', 'fast_config'], function(exports) {
	"use strict";

	/**
	 * Button component
	 * */
	var MOD_NAME = 'domain_design_default',
		$ = layui.jquery,
        api = layui.api,
        fast_config = layui.fast_config
    ;

	var domain_design_default = function(opt) {
		this.option = opt;
	};



    /**
	 * Button start loading
	 * */
    domain_design_default.prototype.render = function(opt) {
		
		var option = {
			elem: opt.elem,
            initData:opt.initData
		}

        var grid;
        var parentContextData = window.parent.window.contextData;
        // var path = parentContextData.contextmenuData.data.path;
        var metaName;


        var dateEditor = function (ui) {
            var $inp = ui.$cell.find("input"),
                grid = this,
                validate = function (that) {
                    var valid = grid.isValid({
                        dataIndx: ui.dataIndx,
                        value: $inp.val(),
                        rowIndx: ui.rowIndx
                    }).valid;
                    if (!valid) {
                        that.firstOpen = false;
                    }
                };

            //initialize the editor
            $inp
                .on("input", function (evt) {
                    validate(this);
                })
                .datepicker({
                    changeMonth: true,
                    changeYear: true,
                    showAnim: '',
                    dateFormat: 'yy-mm-dd',
                    onSelect: function () {
                        this.firstOpen = true;
                        validate(this);
                    },
                    beforeShow: function (input, inst) {
                        return !this.firstOpen;
                    },
                    onClose: function () {
                        this.focus();
                    }
                });
        }


        //called when save changes button is clicked.
        function saveChanges() {

            //attempt to save editing cell.
            if (grid.saveEditCell() === false) {
                return false;
            }

            if ( grid.isDirty() && grid.isValidChange({ focusInvalid: true }).valid ) {

                var changes = grid.getChanges({ format: "byVal" });

                //post changes to server
                api.post({
                    enableRootPath: true,
                    dataType: "json",
                    type: "POST",
                    async: true,
                    beforeSend: function (jqXHR, settings) {
                        grid.showLoading();
                    },
                    url: "/meta/" + metaName + "/batch",
                    // contextT
                    data: JSON.stringify(changes),
                    headers:{'Content-Type':'application/json;charset=utf8'},
                    success: function (changes) {
                        grid.commit({ type: 'add', rows: changes.addList });
                        grid.commit({ type: 'update', rows: changes.updateList });
                        grid.commit({ type: 'delete', rows: changes.deleteList });

                        grid.history({ method: 'reset' });
                    },
                    complete: function () {
                        grid.hideLoading();
                    }
                });
            }
        }

        //获取url中的参数
        function getUrlParam(url, name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
            var r = url.substr(1).match(reg);  //匹配目标参数
            if (r != null) return unescape(r[2]); return null; //返回参数值
        }


        var autoCompleteEditor = function (ui) {
            var $inp = ui.$cell.find("input");

            //initialize the editor
            $inp.autocomplete({
                source: (ui.dataIndx == "books" ? books : "/pro/demos/getCountries"),
                selectItem: { on: true }, //custom option
                highlightText: { on: true }, //custom option
                minLength: 0
            }).focus(function () {
                //open the autocomplete upon focus
                $(this).autocomplete("search", "");
            });
        }

        var data=[
            { fieldComment: "主键", fieldName: "id", columnName: "", fieldType: "basic", fieldClass: "String", canExcel: false, apiHide: true},
            { fieldComment: "创建人", fieldName: "createUserId", columnName: "", fieldType: "basic", fieldClass: "String", canExcel: false, apiHide: true},
            { fieldComment: "创建时间", fieldName: "createTime", columnName: "", fieldType: "basic", fieldClass: "Date", canExcel: false, apiHide: true},
            { fieldComment: "最后修改人", fieldName: "updateUserId", columnName: "", fieldType: "basic", fieldClass: "String", canExcel: false, apiHide: true},
            { fieldComment: "修改时间", fieldName: "updateTime", columnName: "", fieldType: "basic", fieldClass: "Date", canExcel: false, apiHide: true},
            { fieldComment: "拥有机构", fieldName: "ownOrganCode", columnName: "", fieldType: "basic", fieldClass: "String", canExcel: false, apiHide: true},
            { fieldComment: "拥有人", fieldName: "ownUserId", columnName: "", fieldType: "basic", fieldClass: "String", canExcel: false, apiHide: true},
            { fieldComment: "删除标识", fieldName: "isDelete", columnName: "", fieldType: "basic", fieldClass: "Integer", canExcel: false, apiHide: true},
            { fieldComment: "租户", fieldName: "tenantId", columnName: "", fieldType: "basic", fieldClass: "String", canExcel: false, apiHide: true},
            { fieldComment: "备注", fieldName: "remark", columnName: "", fieldType: "basic", fieldClass: "String", canExcel: false, apiHide: true}
        ];

        if(option.initData!= undefined && option.initData.length>0){
            data = option.initData;
        }

        function mappingTextRenderer(ui){
            var rowData = ui.rowData,
                dataIndx = ui.dataIndx;

            rowData.pq_cellcls = rowData.pq_cellcls || {};
            if(rowData[dataIndx] == "basic"){
                return "基础类型";
            }else if(rowData[dataIndx] == "String"){
                return "字符";
            }else if(rowData[dataIndx] == "Date"){
                return "日期";
            }else if(rowData[dataIndx] == "Integer"){
                return "数字";
            }
        }

        var obj = {
            hwrap: false,
            virtualX: true,
            rowBorders: false,
            trackModel: { on: true }, //to turn on the track changes.
            scrollModel: {
                autoFit: true
            },
            swipeModel: { on: false },
            editor: {
                select: true
            },
            bootstrap: { on : false },
            // title: "<b>"+metaName+"</b>",
            height:'flex',
            showTitle: false,
            // title: "<b>"+metaName+"</b>",
            history: function (evt, ui) {
                var $tb = this.toolbar();
                if (ui.canUndo != null) {
                    $("button.changes", $tb).button("option", { disabled: !ui.canUndo });
                }
                if (ui.canRedo != null) {
                    $("button:contains('Redo')", $tb).button("option", "disabled", !ui.canRedo);
                }
                $("button:contains('Undo')", $tb).button("option", { label: 'Undo (' + ui.num_undo + ')' });
                $("button:contains('Redo')", $tb).button("option", { label: 'Redo (' + ui.num_redo + ')' });
            },
            colModel: [
                { title: "名称", width: 220, dataType: "string", dataIndx: "fieldComment"},
                { title: "英文名", width: 220, dataType: "string", dataIndx: "fieldName",
                    editable: function (ui) {
                        return false;
                    }
                },
                { title: "数据类别", width: 220, dataType: "string", dataIndx: "fieldType",
                    editable: function (ui) {
                        return false;
                    },
                    render: mappingTextRenderer
                },
                { title: "字段类型", width: 220, dataType: "string", dataIndx: "fieldClass",
                    editable: function (ui) {
                        return false;
                    },
                    render: mappingTextRenderer
                },
                { title: "可导出", width: 100, dataType: "bool", align: "center", dataIndx: "canExcel",
                    editor: false,
                    type: 'checkbox',
                    validations: [{ type: 'nonEmpty', msg: "Required"}]
                },
                { title: "隐藏参数", width: 100, dataType: "bool", align: "center", dataIndx: "apiHide",
                    editor: false,
                    type: 'checkbox',
                    validations: [{ type: 'nonEmpty', msg: "Required"}]
                }
            ],
            postRenderInterval: -1, //call postRender synchronously.
            create: function(){
                this.widget().pqTooltip();
            },
            dataModel:{data: data},
            // dataModel:{
            //     location: "remote",
            //     dataType: "JSON",
            //     method: "GET",
            //     recIndx: "id",
            //     url: fast_config.api + "/meta/" + metaName,
            //     getData:function( dataJSON, textStatus, jqXHR ){
            //         return { curPage: dataJSON.page.number, totalRecords: dataJSON.page.size, data: dataJSON._embedded.list };
            //     },
            //     beforeSend: function( jqXHR, settings ){
            //         var url = settings.url;
            //         var pq_curpage = getUrlParam(url, 'pq_curpage');
            //         var pq_rpp = getUrlParam(url, 'pq_rpp');
            //         if(pq_curpage){
            //             url += '&page=' + pq_curpage;
            //         }
            //         if(pq_rpp){
            //             url += '&size=' + pq_rpp;
            //         }
            //
            //         settings.url = url;
            //     }
            // },
        };
        grid = pq.grid( option.elem, obj );

        option.grid = grid;

        return new domain_design_default(option);
	}


    exports(MOD_NAME, new domain_design_default());
});
